<template>
  <div>
    <div class="page-container padding-20 query-list-container" v-show="$route.fullPath === $route.matched[1].path">
      <div class="search-container">
        <el-form :inline="true" ref="form" :model="searchData" size="small">
          <el-form-item label="关键字搜索">
            <el-input v-model="searchData.keyword" placeholder="请输入关键字"></el-input>
          </el-form-item>
          <el-form-item label="所属品牌">
            <el-select v-model="searchData.brandId" clearable>
              <el-option
                v-for="brand in brandList"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所在地区" clearable>
            <area-select v-model="searchData.area" 
              :emitPath="true" @labelChange="labelChange" ></area-select>
          </el-form-item>
          <el-button type="primary" @click="onSearch" size="small">查询</el-button>
          <el-button @click="onReset" size="small">重置</el-button>
        </el-form>
      </div>
      <div class="toolbar-container">
        <el-button size="small" @click="batchPause">批量暂停</el-button>
        <el-upload
          class="import-upload"
          accept=".xls,.xlsx"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :headers="importHeaders"
          :action="importCinemaUrl"
          :limit="1">
          <el-button size="small">批量导入</el-button>
        </el-upload>
      </div>
      <el-table class="mt-20 el-table-modify" :data="tableData" border @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="40">
        </el-table-column>
        <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
        <el-table-column prop="cinemaId" align="center" label="站点ID"></el-table-column>
        <el-table-column prop="cinemaName" align="center" label="站点名称"></el-table-column>
        <el-table-column prop="brandName" align="center" label="所属品牌"></el-table-column>
        <el-table-column prop="regionName" align="center" label="所在地区"></el-table-column>
        <el-table-column prop="level" align="center" label="站点等级">
          <template slot-scope="scope">
            {{SITE_LEVEL[scope.row.level]}}
          </template>
        </el-table-column>
        <el-table-column prop="ticketQuantity" align="center" label="售票合计"></el-table-column>
        <el-table-column prop="deviceQuantity" align="center" label="关联设备"></el-table-column>
        <el-table-column prop="status" align="center" label="状态">
          <template slot-scope="scope">
            {{SITE_STATUS[scope.row.status]}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 'NORMAL'">
              <el-button size="mini" type="text" @click="linkToDetail(scope.row)">详情</el-button>
              <el-button size="mini" type="text" @click="linkToEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="text" @click="pauseCinema(scope.row)">暂停开放</el-button>
            </span>
            <el-button v-else-if="scope.row.status == 'EDITING'" size="mini" type="text" @click="linkToEdit(scope.row)">完善信息</el-button>
            <span v-else>
              <el-button size="mini" type="text" @click="linkToDetail(scope.row)">详情</el-button>
              <el-button size="mini" type="text" @click="recoverCinema(scope.row)">恢复开放</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        ref="pagination"
        class="mt-20"
        background
        :page-size.sync="pageOption.pageSize"
        :total="pageOption.total"
        @size-change="onSizeChange"
        @current-change="onPageChange"
        layout="slot,->,prev,pager,next,sizes,jumper"
      >
        <span
            class="pagination-title"
          >共 {{pageOption.total}} 条记录 第 {{pageOption.page}} / {{pageOption.pageTotal}} 页</span>
      </el-pagination>
    </div>

    <div v-if="$route.fullPath !== $route.matched[1].path">
      <router-view v-if="$route.fullPath !== $route.matched[1].path" 
      @refresh="requestData()" :brandList="brandList"></router-view>
    </div>
  </div>
</template>

<script>
import {SITE_STATUS, SITE_LEVEL} from '@/utils/const'
import {cinemaQuery, cinemaDel, cinemaPause, cinemaRecover, importCinemaUrl, cinemaPatchPause } from '@/api/cinema'
import {enableBrands} from '@/api/brand'
import CinemaForm from './CinemaForm';
import AreaSelect from '@/components/AreaSelect';
import { getToken } from '@/utils/auth'

export default {
  name: "cinemaMgt",
  components: { CinemaForm, AreaSelect},
  data() {
    this.SITE_LEVEL = SITE_LEVEL;
    this.SITE_STATUS = SITE_STATUS
    this.importCinemaUrl = importCinemaUrl
    this.importHeaders = {
      token: getToken()
    }

    return {
      brandList: [],
      tableData: [],
      multipleSelection: [],
      searchData: {
        area: [],
        keyword: '',
        brandId: '',
        regionCode: '',
        region: ''
      },
      pageOption: {
        page: 1,
        pageSize: 20,
        total: 0,
        pageTotal: 1
      },
      selectData: null
    };
  },
  methods: {
    labelChange(label) {
      this.searchData.region = label;
    },
    onSearch() {
      this.pageOption.page = 1;
      this.requestData();
    },
    onReset() {
      this.pageOption.page = 1;
      this.searchData = {
        area: [],
        keyword: '',
        brandId: '',
        regionCode: '',
        region: ''
      }
      this.requestData();
    },
    uploadError(err) {
      this.$message.error('导入失败')
    },
    uploadSuccess() {
      this.$message.success('导入成功')
      this.requestData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async batchPause() {
      if (this.multipleSelection.length == 0) {
        return this.$message.warning('请选择站点')
      }
      try {
        await cinemaPatchPause(this.multipleSelection.map(item => item.cinemaId))
        this.$message.success('批量暂停成功')
        this.requestData() 
      } catch (error) {
        
      }
    },
    linkToEdit(row) {
      this.selectData = row; 
      this.$router.push({name: 'editCinema', params: {id: row.cinemaId}})
    },
    linkToDetail(row) {
      this.selectData = row;
      this.$router.push({name: 'cinemaDetail', params: {id: row.cinemaId}})
    },
    onSizeChange(size) {
      this.pageOption.pageSize = size;
      this.requestData();
    },
    onPageChange(page) {
      this.pageOption.page = page;
      this.requestData();
    },
    async requestData() {
      const {page, pageSize : size} = this.pageOption
      const postData = {};
      Object.keys(this.searchData).forEach(item => {
        if (this.searchData[item]) {
          postData[item] = this.searchData[item];
        }
      })
      if (postData.area.length > 0) {
        postData.regionCode = postData.area.join(',')
      }
      const {data, total} = await cinemaQuery({page: page - 1, size, ...postData})
      let pageTotal = Math.ceil(total / size);
      this.tableData = data;
      this.pageOption.total = total;
      this.pageOption.pageTotal = pageTotal || 1
      this.multipleSelection = []

      if (this.$refs.pagination) {
        let childrenRefs = this.$refs.pagination.$children
        this.$nextTick(() => {
          childrenRefs.forEach(child => child.$forceUpdate())
        });
      }
    },
    async requestBrand() {
      const {data} = await enableBrands();
      this.brandList = data;
    },
    async pauseCinema(row) {
      this.$confirm('确定要暂停开放该站点吗？<br/>暂停后该站点将无法正常使用', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
        callback: async (action) => {
          if (action == 'confirm') {
            const {data} = await cinemaPause(row.cinemaId);
            this.requestData();
          }
        }
      });
    },
    async recoverCinema(row) {
      this.$confirm('确定要恢复开放该站点吗？', {
        type: 'warning',
        callback: async (action) => {
          if (action == 'confirm') {
            const {data} = await cinemaRecover(row.cinemaId);
            this.requestData();
          }
        }
      });
    }
  },
  created() {
    this.requestData();
    this.requestBrand();
  }
};
</script>

<style lang="scss">
.import-upload {
  display: inline;

  .el-upload-list {
    display: none;
  }
}
</style>